<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 云课堂
 *
 * @icon fa fa-user
 */
class Category extends Backend
{
    /**
     * @var \app\admin\model\AuthRule
     */
    protected $model = null;
    protected $rulelist = [];
    protected $multiFields = 'ismenu,status';

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Subject.Category');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
     /**
     * 添加
     */
    public function add(){
        if($this->request->isPost()){
            $params=$this->request->post('row/a');
            if(empty($params)){
                $this->error("参数不能为空");
            }
            $result=$this->model->validate('common/Subject/Category')->save($params);
            if(!$result){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {    $category=$this->model->find($ids);
        if(!$category){
            $this->error(__('当前分类不存在'));
        }
        if($this->request->isPost()){
            $params=$this->request->post('row/a');
            $params['id']=$ids;
            if(empty($params)){
                $this->error("参数不能为空");
            }
            if($category['name']!=$params['name']||$category['weight']!=$params['weight']){
                $result=$this->model->isUpdate()->save($params);
                if(!$result){
                    $this->error();
                }
            }
            $this->success();
        }
    
        $this->assign('category',$category);
        return $this->view->fetch();
    }
     /**
     * 删除
     */
    public function del($ids = null)
    {
        $categoryList=$this->model->all($ids);
        if(empty($categoryList)){
            $this->error('当前分类不存在');
        }
        $result=$this->model->destroy($ids);
        if(!$result){
            $this->error($this->model->getError());
        }
        $this->success();
    }
}
